// filename: frontend/src/pages/index/index.vue

<template>
  <Header @open-auth-modal="isAuthModalVisible = true" />
  <AuthModal v-if="isAuthModalVisible" @close="isAuthModalVisible = false" />

  <div class="page-container" @click="handlePageClick" style="padding-top: 60px;">
    <div class="content-wrapper">
      <header class="page-header">
        <div class="header-left">
          <h1>当前列表</h1>
          <span class="song-count">{{ listSummary }}</span>
        </div>
        <div class="header-right">
          <div class="download-btn" @click="handleDownloadCurrentList">
            <svg width="24" height="24" viewBox="0 0 24" fill="currentColor">
              <path d="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z" />
            </svg>
            <span>下载当前列表</span>
          </div>
        </div>
      </header>

      <SearchBar
        ref="searchBarRef"
        @search="handleSearch"
        @focus="handleSearchBarFocus"
      />
      
      <ListControls
        :pagination="pagination"
        :current-sort="currentSort"
        @update:page="handlePageChange"
        @update:sort="handleSortChange"
      />

      <main style="position: relative; flex: 1" :class="{ loading: isLoading }">
        <div class="song-list" v-if="songList.length > 0">
          <SongCard
            v-for="song in songList"
            :key="song.id"
            :ref="(el) => setSongCardRef(song.id, el)"
            :song="song"
            @filter="handleSongCardFilter"
            @menuToggled="handleMenuToggled"
            @play="handlePlaySong"
            @refresh-request="handleSongRefreshRequest"
          />
        </div>

        <view v-if="!isLoading && songList.length === 0" class="empty-state">
          <text>没有找到任何歌曲 ╮(╯▽╰)╭</text>
        </view>
      </main>
    </div>
    <Player v-if="playerStore.showPlayer" />
  </div>
</template>

<script setup>
import { onShow, onHide, onLoad, onUnload } from "@dcloudio/uni-app";
import { computed, nextTick, onBeforeUpdate, reactive, ref } from "vue";
import { usePlayerStore } from "@/store/player";
import { useSearchStore } from "@/store/search";
import { useAuthStore } from "@/store/auth";
import { request } from "@/utils/request"; // 【核心修改1】导入 request
import { downloadSongs } from "@/utils/download.js";

import Header from "@/components/Header/Header.vue";
import AuthModal from "@/components/AuthModal/AuthModal.vue";
import ListControls from "@/components/ListControls/ListControls.vue";
import Player from "@/components/Player.vue";
import SearchBar from "@/components/SearchBar/SearchBar.vue";
import SongCard from "@/components/SongCard/SongCard.vue";

const playerStore = usePlayerStore();
const searchStore = useSearchStore();
const authStore = useAuthStore();
const isAuthModalVisible = ref(false);

const songList = ref([]);
const isLoading = ref(true);
const searchBarRef = ref(null);
const songCardRefs = ref({});
const openedMenuCardId = ref(null);

const pendingHighlight = ref(null);

const pagination = reactive({
  current_page: 1,
  total_pages: 1,
  total_songs: 0,
  limit: 100,
});
const currentSort = ref('date_desc');
const currentSearch = reactive({ type: 'all', value: '' });

const listSummary = computed(() => {
  if (currentSearch.value.value) {
    return `共找到 ${pagination.total_songs} 首歌`;
  }
  return `共 ${pagination.total_songs} 首歌`;
});

// --- 【核心修改2】重写 handleSongRefreshRequest ---
const handleSongRefreshRequest = async (payload) => {
  const { songId } = payload;
  const indexToUpdate = songList.value.findIndex(s => s.id === songId);
  if (indexToUpdate === -1) return;

  try {
    const freshSongData = await request({
      url: `/api/songs/${songId}`,
      method: 'GET'
    });
    if (freshSongData) {
      songList.value[indexToUpdate] = freshSongData;
    }
  } catch (error) {
    console.warn(`Failed to refresh song ${songId}:`, error);
  }
};

// --- 【核心修改3】重写 fetchSongs ---
const fetchSongs = async (page = pagination.current_page, sortBy = currentSort.value) => {
  isLoading.value = true;
  
  const params = new URLSearchParams({
    page: page,
    limit: pagination.limit,
    sort_by: sortBy,
  });
  
  let url = '';
  if (currentSearch.type === 'all' || !currentSearch.value) {
    url = `/api/songs?${params.toString()}`;
  } else {
    params.append('type', currentSearch.type);
    params.append('value', currentSearch.value);
    url = `/api/songs/filter?${params.toString()}`;
  }
  
  try {
    const data = await request({
      url: url,
      method: 'GET'
    });

    if (data && data.songs) {
      songList.value = data.songs || [];
      Object.assign(pagination, data.pagination);
      
      if (pendingHighlight.value) {
        nextTick(() => {
          const task = pendingHighlight.value;
          const cardRef = songCardRefs.value[task.songId];
          
          if (cardRef && cardRef.$el) {
            cardRef.$el.scrollIntoView({ behavior: "smooth", block: "center" });
            
            if (task.openComment) {
              cardRef.openCommentModal({ 
                parentId: task.parentId, 
                commentId: task.commentId 
              });
            } else {
              playerStore.setPlaylistAndPlay(songList.value, task.songId);
            }
          }
          pendingHighlight.value = null;
        });
      }
    } else {
      songList.value = [];
      Object.assign(pagination, { total_songs: 0 });
    }
  } catch (error) {
    console.error("Failed to fetch songs:", error);
    songList.value = [];
    Object.assign(pagination, { total_songs: 0 });
  } finally {
    isLoading.value = false;
    if (!pendingHighlight.value) {
      uni.pageScrollTo({ scrollTop: 0, duration: 200 });
    }
  }
};

// --- 【核心修改4】重写 onLoad 中的 uni.request ---
onLoad(async (options) => {
  const songId = options.songId;
  if (songId) {
    uni.showLoading({ title: '正在定位分享歌曲...' });
    try {
      const jumpTask = await request({
        url: `/api/songs/location/${songId}`,
        method: 'GET'
      });
      
      if (jumpTask) {
        pagination.current_page = jumpTask.page;
        currentSort.value = jumpTask.sort_by;
        pendingHighlight.value = {
          songId: Number(songId),
          openComment: false,
        };
        fetchSongs(jumpTask.page, jumpTask.sort_by);
      }
    } catch (error) {
      uni.showToast({ title: '找不到分享的歌曲', icon: 'none' });
      fetchSongs(1, 'date_desc');
    } finally {
      uni.hideLoading();
    }
  } else {
    fetchSongs(1, 'date_desc');
  }
});

// --- 其他函数保持不变或微调 ---

const handleSortChange = (newSort) => {
  currentSort.value = newSort;
  pagination.current_page = 1;
  fetchSongs(1, newSort);
};

const handlePageChange = (newPage) => {
  pagination.current_page = newPage;
  fetchSongs(newPage);
};

const handleSearch = (payload) => {
  currentSearch.type = payload.type;
  currentSearch.value = payload.value.trim();
  pagination.current_page = 1;
  fetchSongs();
};

const handlePlaySong = (songId) => {
  playerStore.setPlaylistAndPlay(songList.value, songId);
};

const handleDownloadCurrentList = () => {
  const ids = songList.value.map((song) => song.id);
  downloadSongs(ids);
};

const handleNavigateToComment = (data) => {
  const { song_id, parent_id, comment_id } = data;
  if (!song_id) return;

  nextTick(() => {
    const cardRef = songCardRefs.value[song_id];
    if (cardRef) {
      cardRef.$el.scrollIntoView({ behavior: 'smooth', block: 'center' });
      cardRef.openCommentModal({ 
        parentId: parent_id ? parseInt(parent_id, 10) : null, 
        commentId: comment_id ? parseInt(comment_id, 10) : null 
      });
    } else {
        uni.showToast({ title: '目标歌曲不在当前页面，请先搜索找到它', icon: 'none' });
    }
  });
};

const handleSearchFromEmit = (payload) => {
    if (payload && payload.type && payload.value && searchBarRef.value) {
        searchBarRef.value.setSearchTextAndExecute(String(payload.value));
    }
};

onShow(() => {
  uni.$on('navigateToComment', handleNavigateToComment);
  uni.$on('forceSearch', handleSearchFromEmit);

  if (searchStore.pendingJump) {
    const jumpTask = { ...searchStore.pendingJump };
    searchStore.clearPendingJump();

    pendingHighlight.value = {
      songId: jumpTask.highlight_song_id,
      openComment: jumpTask.open_comment,
      commentId: jumpTask.highlight_comment_id,
      parentId: jumpTask.highlight_parent_id,
    };
    
    currentSort.value = jumpTask.sort_by;
    pagination.current_page = jumpTask.page;
    fetchSongs(jumpTask.page, jumpTask.sort_by);
    
    return;
  }

  if (searchStore.pendingSearch) {
    const { type, value } = searchStore.pendingSearch;
    searchStore.clearPendingSearch();
    if (searchBarRef.value) {
      searchBarRef.value.setSearchTextAndExecute(value);
    }
  }
});

onHide(() => {
    uni.$off('navigateToComment', handleNavigateToComment);
    uni.$off('forceSearch', handleSearchFromEmit);
});

onUnload(() => {
  uni.$off('navigateToComment', handleNavigateToComment);
  uni.$off('forceSearch', handleSearchFromEmit);
});

// --- 无需修改的辅助函数 ---
const setSongCardRef = (id, el) => { if (el) { songCardRefs.value[id] = el; } };
onBeforeUpdate(() => { songCardRefs.value = {}; });
const handleSongCardFilter = (searchTerm) => { if (searchBarRef.value) { searchBarRef.value.setSearchTextAndExecute(searchTerm); } };
const handleMenuToggled = (payload) => {
  const { id, isOpen } = payload;
  if (isOpen) {
    if (openedMenuCardId.value && openedMenuCardId.value !== id) {
      const oldCard = songCardRefs.value[openedMenuCardId.value];
      if (oldCard) oldCard.closeMenu();
    }
    openedMenuCardId.value = id;
  } else if (openedMenuCardId.value === id) {
    openedMenuCardId.value = null;
  }
};
const closeAnyOpenMenu = () => { if (openedMenuCardId.value) { const card = songCardRefs.value[openedMenuCardId.value]; if (card) card.closeMenu(); } };
const handlePageClick = () => { if (searchBarRef.value) { searchBarRef.value.closeSearchResults(); } closeAnyOpenMenu(); };
const handleSearchBarFocus = () => { closeAnyOpenMenu(); };

</script>

<style scoped>
.page-container {
  display: flex;
  justify-content: center;
  width: 100%;
  height: 100%;
}
.content-wrapper {
  width: 100%;
  max-width: 800px;
  background-color: #ffffff;
  display: flex;
  flex-direction: column;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 20px 10px 20px;
}
.header-left {
  display: flex;
  align-items: baseline;
}
.download-btn {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background-color: #f0f0f0;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.2s;
}
.download-btn:hover {
  background-color: #e0e0e0;
}
.download-btn span {
  margin-left: 8px;
  font-size: 14px;
  font-weight: 500;
}
.page-header h1 {
  font-size: 24px;
  font-weight: bold;
  margin: 0;
}
.song-count {
  margin-left: 15px;
  font-size: 16px;
  color: #888;
}
.song-list {
  padding: 0 20px;
  margin-block-end: 150px;
  transition: opacity 0.3s ease;
}
main.loading .song-list {
  opacity: 0.6;
  pointer-events: none;
}
.empty-state {
  padding: 60px 20px;
  text-align: center;
  color: #888;
  font-size: 16px;
}
</style>